const btn = document.querySelector('#search')
const ipt = document.querySelector("#city")
const tbody = document.querySelector('tbody')



function request(city, callback) {
    const url = `http://wthrcdn.etouch.cn/weather_mini?city=${city}`
    //4.实例化一个XMLhttpRequest对象
    const xhr = new XMLHttpRequest()
    //5.初始化一个请求
    xhr.open("GET", url)
    //6.发送请求
    xhr.send()
    //7.监听状态改变
    xhr.onreadystatechange = function () {
        console.log(xhr.readyState)
        //8.响应成功且已经下载好数据
        if (xhr.readyState == 4 && xhr.status == 200) {
            //9.把响应的JSON格式的字符串解析为对象
            const data = JSON.parse(xhr.responseText)
            // console.log(data)
            //10.获取天气预报数据
            const forecast = data.data.forecast
            // console.log(forecast)
            callback(forecast)
            console.log(JSON.stringify(forecast) )
        }

    }
}


function render(forecast) {
    let htmlStr = ''
    //11.循环天气预报数组
    for (let i = 0; i < forecast.length; i++) {
        //12.拿到数组里面的每个元素
        const item = forecast[i]
        // console.log(item)
        //13.根据对象生成html片段
        const fengli = /\d{1,2}级/.exec(item.fengli)[0]
        const trHtml = `
                <tr>
                    <td>${item.date}</td>
                    <td>${fengli}</td>
                    <td>${item.fengxiang}</td>
                    <td>${item.high}</td>
                    <td>${item.low}</td>
                    <td>${item.type}</td>
                </tr>`
        //14.拼接到htmlStr
        htmlStr += trHtml
    }
    console.log(htmlStr)
    //15.把html字符串渲染到tbody里面
    tbody.innerHTML = htmlStr

}

btn.onclick = function () {
    const city = ipt.value
    request(city,render)
}
